<template>
  <el-container>
    <!-- Sidebar -->
    <el-aside width="240px" class="bg-gray-50 p-4 border-r">
      <!-- <div class="head-container">
        <el-input v-model="deptName" placeholder="请输入分类名称" clearable prefix-icon="Search" style="margin-bottom: 20px" />
      </div> -->
      <div class="head-container">
        <el-tree
          :data="treeData"
          :props="defaultProps"
          node-key="id"
          highlight-current
          default-expand-all
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <div class="flex justify-between items-center w-full">
              <span>{{ data.deptName || data.buildingName || data.floorName }}</span>
              <el-dropdown>
                <span class="el-dropdown-link">
                  <el-icon><MoreFilled /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item v-if="!data.floorId" @click="addChild(data)">添加下级组织</el-dropdown-item>
                    <el-dropdown-item @click="editNode(data)">编辑本组织</el-dropdown-item>
                    <el-dropdown-item @click="deleteNode(data)"
                      ><el-text type="danger">删除</el-text></el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-tree>
      </div>
    </el-aside>

    <!-- Main content -->
    <el-container>
      <el-header class="flex items-center p-4">
        <div class="searchStyle">
          <div>
            <el-input
              v-model="queryParams.roomName"
              placeholder="房间号查询"
              :prefix-icon="Search"
              style="width: 200px; margin-right: 15px"
              @keyup.enter="handleQuery"
            />
          </div>
          <div>
            <!--           
          <el-select
              v-model="queryParams.roomType"
              style="width: 200px;margin-right: 15px;"
              placeholder="全部类型"
              @change="handleQuery"
              clearable
            >
              <el-option
                v-for="item in typeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select> -->
            <el-input
              v-model="queryParams.roomType"
              placeholder="全部类型"
              :prefix-icon="Search"
              style="width: 200px; margin-right: 15px"
              @keyup.enter="handleQuery"
            />
          </div>
        </div>
        <div>
          <el-button type="primary" plain @click="handleAdd" v-hasPermi="['system:setting:add']"
            >新建</el-button
          >
        </div>
      </el-header>

      <el-main class="p-4">
        <el-table :data="tableData">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="roomName" label="区域名称" width="100" />
          <el-table-column prop="sectionType" label="区域类型" />
          <el-table-column prop="didNumber" label="分机号" />
          <el-table-column prop="roomType" label="客房类型" />
          <el-table-column prop="responsibleName" label="场所责任人" />
          <el-table-column label="操作" width="180">
            <template #default="{ row }">
              <el-button type="text" icon="Edit" @click="editRow(row)">编辑</el-button>
              <el-button type="danger" icon="Delete" text="danger" @click="deleteRow(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-main>
    </el-container>
    <!-- 新增tree对话框 -->
    <el-dialog :title="treeDialogObj.title" v-model="treeDialogObj.open" append-to-body>
      <el-form
        ref="settingRef"
        :model="treeDialogObj.form"
        :rules="treeDialogObj.rules"
        label-width="110px"
        label-position="top"
      >
        <el-form-item label="组织名称" prop="name">
          <el-input v-model="treeDialogObj.form.name" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增表格对话框 -->
    <el-dialog
      :title="tableDialogObj.title"
      v-model="tableDialogObj.open"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="tableSettingRef"
        :model="tableDialogObj.form"
        :rules="tableDialogObj.rules"
        label-width="110px"
        label-position="top"
      >
        <el-form-item label="区域名称" prop="roomName">
          <el-input v-model="tableDialogObj.form.roomName" />
        </el-form-item>
        <el-form-item label="客房类型" prop="roomType">
          <el-input v-model="tableDialogObj.form.roomType" />
        </el-form-item>
        <el-form-item label="区域类型" prop="sectionType">
          <el-select v-model="tableDialogObj.form.sectionType" placeholder="请选择区域类型" style="flex: 1;">
            <el-option v-for="item in regionOption" :key="item"
              :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="场所负责人" prop="responsibleId">
          <el-tree-select
            v-model="tableDialogObj.form.responsibleId"
            :data="userOptions"
            :render-after-expand="false"
            show-checkbox
            :props="{
              value: 'id',
              label: 'label',
              children: 'children',
              // 可选：禁用用户节点选择
              disabled: (data) => !data.isUser,
            }"
            check-strictly
            check-on-click-node
            node-key="id"
            filterable
            style="width: 100%"
            placeholder="选择责任人"
          />
        </el-form-item>  
        <el-form-item 
          label="分机号" 
          prop="didNumber" 
        >
          <div v-for="(domain, index) in tableDialogObj.form.didNumber" :key="index" style="width: 100%;">
              <el-input
                style="width: 95%;margin: 3px 0;"
                v-model="domain.value"
              />
              <el-button
                v-if="tableDialogObj.form.didNumber.length > 1"
                link
                type="danger"
                text='danger'
                icon="Delete"
                @click="hoursDelete(index)"
                ></el-button>
            </div>
        </el-form-item>
        <el-button
            link
            type="primary"
            icon="CirclePlus"
            @click="addDomain"
            >添加</el-button
          >
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="tableCancel">取 消</el-button>
          <el-button type="primary" @click="tableSubmitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </el-container>
</template>

<script setup name="roomInfo">
import { ref, reactive } from "vue"
import { MoreFilled, Calendar, Search, Share } from "@element-plus/icons-vue"
import useUserStore from "@/store/modules/user"
import { deptUserTree } from "@/api/system/role"
import { ElMessageBox } from "element-plus"
import {
  getFloorList,
  getRoomList,
  addRoom,
  putRoom,
  delSettingroom,
  addFloor,
  putFloor,
  delSettingFloor,
  addBuilding,
  putBuilding,
  deleteBuilding,
  getSectionType,
} from "@/api/system/setting"

const { proxy } = getCurrentInstance()

const loading = ref(true)
const total = ref(10)
const typeOption = ref([])

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  roomName: null,
  roomType: null,
  floorId: null,
})

const treeData = ref([])
const regionOption = ref([])
// 获取工单类型
getSectionType().then((response) => {
  regionOption.value = response.data
})
const defaultProps = {
  children: "children",
}
const getFloorListFn = () => {
  getFloorList().then((response) => {
    treeData.value = traverseTree([response.data])
  })
}
getFloorListFn()

const tableData = ref([])

// 点击树节点时的回调函数
const handleNodeClick = (data) => {
  console.log("Node clicked:", data)
  if (data.floorId) {
    // 楼层
    queryParams.floorId = data.floorId
    getList()
  }
}

const settingRef = ref(null)
const treeDialogObj = reactive({
  open: false,
  title: "",
  type: 1,
  form: {
    name: null,
  },
  rules: {
    name: [{ required: true, message: "请输入组织名称", trigger: "blur" }],
  },
})
// 树-添加按钮操作
const addChild = (data) => {
  treeDialogObj.open = true
  treeDialogObj.title = "添加下级组织"
  treeDialogObj.type = 1
  // 判断是添加楼层
  treeDialogObj.form.buildingId = data.buildingId ? data.buildingId : null
  console.log("添加子节点", data)
}
// 树-编辑按钮操作
const editNode = (data) => {
  treeDialogObj.open = true
  treeDialogObj.title = "编辑本组织"
  treeDialogObj.type = 2
  // 判断当前编辑的是楼栋还是楼层
  treeDialogObj.form = data
  if (data.floorId) {
    // 楼层
    treeDialogObj.form.name = data.floorName
  } else {
    // 楼栋
    treeDialogObj.form.name = data.buildingName
  }
}
// 树-删除按钮操作
const deleteNode = (data) => {
  ElMessageBox.confirm("确定删除?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "error",
  })
    .then(() => {
      // 删除楼层
      if (data.floorId) {
        delSettingFloor(data.floorId).then((response) => {
          proxy.$modal.msgSuccess("删除楼层成功")
          getFloorListFn()
        })
      } else {
        // 删除楼栋
        deleteBuilding(data.buildingId).then((response) => {
          proxy.$modal.msgSuccess("删除楼栋成功")
          getFloorListFn()
        })
      }
      console.log("删除节点", node)
    })
    .catch(() => {})
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

/** 查询【请填写功能名称】列表 */
function getList() {
  if (!queryParams.floorId) {
    return proxy.$modal.msgWarning("请先选择楼层！")
  }
  loading.value = true
  getRoomList(queryParams).then((response) => {
    tableData.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

const tableSettingRef = ref(null)
const tableDialogObj = reactive({
  open: false,
  title: "",
  form: {
    roomName: null,
    roomType: null,
    responsibleId: null,
    sectionType: null,
    didNumber: [{value:''}],
  },
  rules: {
    roomName: [{ required: true, message: "请输入区域名称", trigger: "blur" }],
    roomType: [{ required: false, message: "请输入客房类型", trigger: "blur" }],
    sectionType: [{ required: true, message: "请选择区域类型", trigger: "change" }],
    responsibleId: [{ required: true, message: "请选择责任人", trigger: "change" }],
  },
})
const addDomain = () => {
  tableDialogObj.form.didNumber.push({
    value: '',
  })
}
const hoursDelete = (index) => {
  tableDialogObj.form.didNumber.splice(index, 1)
}
// 表格-取消按钮操作
const tableCancel = () => {
  tableDialogObj.open = false
  tableSettingRef.value.resetFields()
}

// 表格-确定按钮操作
const tableSubmitForm = () => {
  tableSettingRef.value.validate((valid) => {
    if (valid) {
      // 提交表单数据
      const params = {
        ...tableDialogObj.form,
        floorId: queryParams.floorId,
        didNumber: tableDialogObj.form.didNumber.map(item => item.value).join(',')
      }
      if (tableDialogObj.form.roomId) {
        params.roomId = tableDialogObj.form.roomId
        putRoom(params).then((response) => {
          proxy.$modal.msgSuccess("修改成功")
          handleQuery()
        })
        // 关闭弹窗
        tableDialogObj.open = false
      } else {
        addRoom(params).then((response) => {
          proxy.$modal.msgSuccess("新增成功")
          handleQuery()
        })
        // 关闭弹窗
        tableDialogObj.open = false
      }
    } else {
      console.log("表单验证失败")
      return false
    }
  })
}

// 表格-新增按钮操作
const handleAdd = () => {
  if (!queryParams.floorId) {
    return proxy.$modal.msgWarning("请先选择楼层！")
  }
  proxy.resetForm("tableSettingRef")
  tableDialogObj.form = {roomName: null,
    roomType: null,
    responsibleId: null,
    sectionType: null,
    didNumber: [{value:''}]}
  tableDialogObj.title = "新增房间"
  tableDialogObj.open = true
}
const convertStringToArray = (str) => {
  return str.split(',').map(item => ({
    value: parseInt(item.trim(), 10)
  }));
};
// 表格-编辑按钮操作
const editRow = (row) => {
  proxy.resetForm("tableSettingRef")
  tableDialogObj.title = "编辑房间"
  tableDialogObj.open = true
  tableDialogObj.form = JSON.parse(JSON.stringify(row))
  tableDialogObj.form.responsibleId = Number(tableDialogObj.form.responsibleId)
  tableDialogObj.form.didNumber = (row.didNumber && convertStringToArray(row.didNumber)) || [{value:''}]
}

// 表格-删除按钮操作
const deleteRow = (row) => {
  ElMessageBox.confirm("确定删除?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "error",
  })
    .then(() => {
      delSettingroom(row.roomId).then((response) => {
        proxy.$modal.msgSuccess("删除成功")
        handleQuery()
      })
      console.log("删除行", row)
    })
    .catch(() => {})
}

// 弹窗-确定按钮操作
const submitForm = () => {
  settingRef.value.validate((valid) => {
    if (valid) {
      // 提交表单数据
      if (treeDialogObj.type == 1) {
        // 新增
        if (treeDialogObj.form.buildingId) {
          // 添加楼层
          addFloor({
            floorName: treeDialogObj.form.name,
            buildingId: treeDialogObj.form.buildingId,
          }).then((response) => {
            proxy.$modal.msgSuccess("添加楼层成功")
            getFloorListFn()
            // 关闭弹窗
            cancel()
          })
        }else{
          addBuilding({
            buildingName: treeDialogObj.form.name,
          }).then((response) => {
            proxy.$modal.msgSuccess("添加楼栋成功")
            getFloorListFn()
            // 关闭弹窗
            cancel()
          })
        }
      } else {
        // 修改
        if (treeDialogObj.form.floorId) {
          // 楼层
          let form = JSON.parse(JSON.stringify(treeDialogObj.form))
          form.floorName = form.name
          putFloor(form).then((response) => {
            proxy.$modal.msgSuccess("编辑楼层成功")
            getFloorListFn()
            // 关闭弹窗
            cancel()
          })
        } else {
          // 楼栋
          let form = JSON.parse(JSON.stringify(treeDialogObj.form))
          form.buildingName = form.name
          putBuilding(form).then((response) => {
            proxy.$modal.msgSuccess("编辑楼栋成功")
            getFloorListFn()
            // 关闭弹窗
            cancel()
          })
        }
      }
    } else {
      console.log("表单验证失败")
      return false
    }
  })
}

// 弹窗-取消按钮
function cancel() {
  treeDialogObj.open = false
  treeDialogObj.form = {
    name: null,
  }
  settingRef.value.resetFields()
}

const userOptions = ref([])

// 获取下拉数据
useUserStore()
  .getInfo()
  .then((res) => {
    // 获取责任人
    deptUserTree({ deptId: res.user.dept.deptId }).then((response) => {
      if (response.code == 200) {
        userOptions.value = [transformDeptTree(response.data, true)]
      }
    })
  })

function transformDeptTree(deptNode, isRoot = false) {
  // 1. 处理当前部门节点
  const transformedNode = {
    id: deptNode.deptId,
    label: deptNode.deptName,
    children: [],
  }

  // 2. 合并用户到同层级children（优先处理用户）
  if (deptNode.userList?.length > 0) {
    transformedNode.children.push(
      ...deptNode.userList.map(user => ({
        id: user.userId,
        label: `${user.nickName} (${user.userName})`,
        isUser: true
      }))
    )
  }

  // 3. 递归处理子部门
  if (deptNode.children?.length > 0) {
    transformedNode.children.push(...deptNode.children.map((child) => transformDeptTree(child)))
  }

  // 4. 根节点特殊处理：将第一个子元素移到最前
  if (isRoot && transformedNode.children.length > 0) {
    const firstChild = transformedNode.children.shift()
    transformedNode.children.unshift(firstChild) // 显式确保顺序
  }

  // 5. 处理空children
  if (transformedNode.children.length === 0) {
    delete transformedNode.children
  }

  return transformedNode
}

function traverseTree(tree) {
  // 遍历树的每个节点
  tree.forEach(node => {
    // 如果当前节点有子节点，递归调用
    node.children = node.buildingList || node.floorList // 确保children存在
    if (node.children && node.children.length > 0) {
      traverseTree(node.children);
    }
  });

  return tree
}
</script>

<style scoped>
.el-table .el-button {
  padding: 0 5px;
}
.searchStyle {
  display: flex;
}
</style>
